﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using SmartForm.Common;
using SmartForm.Rule;

namespace SmartForm
{
    [ComVisible(true)]
    public partial class Main : BaseForm
    {
        BigForm bigForm = new BigForm();
        SystemRule systemRule = new SystemRule();

        public Main()
        {
            IEVersion.SetWebBrowserFeatures(IEVersion.GetBrowserVersion());
            InitializeComponent();
        }

        private void Main_Load(object sender, EventArgs e)
        {
            //大表单 
            bigForm.LoginToken = "123456";
            bigForm.SystemIds = new List<string>() { "1" };
            bigForm.TypeId = "101";
            bigForm.FormOptionList = new List<FormOption>()
            {
                //智慧党建
                //new FormOption(){ Name="ProposalCategoryId",Value="7796771317302272",InputType=InputType.Text, Title="建议类型"},
                //new FormOption(){ Name="Title",Value="智能表单标题",InputType=InputType.Text, Title="建议标题"},
                //new FormOption(){ Name="Content",Value="智能表单内容",InputType=InputType.Text, Title="建议内容"},

                //百度贴吧提问
            };

            //系统规则
            systemRule.ID = "1";
            systemRule.SystemId = "1";
            systemRule.TypeId = "101";
            systemRule.Account = "13389669273";
            systemRule.Password = "zlinkgroup2018";
            systemRule.LoginUrl = "https://www.baidu.com/";
            //systemRule.LoginUrl = "http://zhdj.zlinkgroup.com/";
            systemRule.LoginJS = new List<ExecuteJS>() {
                //智慧党建
                //new ExecuteJS() { JS = "document.getElementsByName('mobile')[0].value='18223277003';", Second = 1 },
                //new ExecuteJS() { JS = "document.getElementsByName('password')[0].value='1234567';", Second = 1 },
                //new ExecuteJS() { JS = "document.getElementById('submit_btn').click();return $('#manage').is(':visible');", Second = 3 },
                //new ExecuteJS() { JS = "location.href='http://zhdj.zlinkgroup.com/page/user/module/feedback/add.html'", Second = 3 }


                //百度贴吧提问
                //new ExecuteJS() { JS = "$('a.lb').click();", Second = 1 }, //点击登录
                //new ExecuteJS() { JS = "return $('#TANGRAM__PSP_10__qrcode').is(':visible');", Second = 1,}, //延迟判断
                //new ExecuteJS() { JS = "document.getElementById('TANGRAM__PSP_10__footerULoginBtn').click();", Second = 1 }, //点击         
                //new ExecuteJS() { JS = " return $('#passport-login-pop-api').is(':visible');", Second = 1 }, //延迟判断
                //new ExecuteJS() { JS = "$('#TANGRAM__PSP_10__userName').val('$account');", Second = 1 }, //账号
                //new ExecuteJS() { JS = "$('#TANGRAM__PSP_10__password').val('$password');", Second = 1 }, //密码
                //new ExecuteJS() { JS = "document.getElementById('TANGRAM__PSP_10__submit').click();", Second = 1 }, //登录
                new ExecuteJS() { JS = "location.href='https://zhidao.baidu.com/new?word=&ie=GBK'", Second = 3 }, //提问页面
            };
            systemRule.FormOptionJSList = new List<FormOptionJS>()
            {
                //new FormOptionJS(){  JS="document.getElementById('CategoryId').value='$value'",Name="ProposalCategoryId", Value="7796771317302272"},
                //new FormOptionJS(){  JS="document.getElementsByName('Title')[0].value='$value'",Name="Title", Value="智能表单标题"},
                //new FormOptionJS(){  JS="document.getElementsByName('Content')[0].value='$value'",Name="Content", Value="智能表单填写内容"},
                //new FormOptionJS(){  JS="document.getElementById('btnSave').click()", Value="智能表单 - 发表按钮",Submit=true},


                new FormOptionJS(){  JS="document.getElementById('title-area').value='$value';",Name="Title", Value="请问智能表单填写怎么做？"},
                new FormOptionJS(){  JS="document.getElementById('content-area').value='$value';",Name="Content", Value="工作中有很多重复的工作，请问智能表单填写怎么做？"},
                new FormOptionJS(){  JS="document.getElementsByClassName('cb-status')[0].click();",Name="Status",Second=1},
                new FormOptionJS(){  JS="document.getElementById('submit-btn').click();", Value="智能表单 - 发表按钮",Submit=true},
            };

            InitWebBrowser();
        }

        /// <summary>
        /// 浏览器初始化
        /// </summary>
        void InitWebBrowser()
        {
            ieWebBrowser.Navigate(new Uri(systemRule.LoginUrl));
            ieWebBrowser.ScriptErrorsSuppressed = true;
            ieWebBrowser.ObjectForScripting = this;
            ObjectForScriptingHelper helper = new ObjectForScriptingHelper(this);
            ieWebBrowser.ObjectForScripting = helper;
        }

        #region 执行JS
        /// <summary>
        /// 执行js并且访问成功才能执行下一步
        /// </summary>
        /// <param name="jsStr"></param>
        public void ExeScript(string jsStr)
        {
            string funcName = "_" + Guid.NewGuid().ToString("N");
            HtmlElement element2 = ieWebBrowser.Document.CreateElement("script");
            element2.SetAttribute("type", "text/javascript");
            element2.SetAttribute("text", "function " + funcName + "(){ " + jsStr + " }");   //这里写JS代码
            HtmlElement head = ieWebBrowser.Document.Body.AppendChild(element2);
            bool isOk = (bool)ieWebBrowser.Document.InvokeScript(funcName);
            Console.Write("返回状态" + isOk.ToString());
            if (!isOk)
            {
                //执行js未成功，1秒后重试
                Delay(1);
                ExeScript(jsStr);
            }
        }
        /// <summary>
        /// 使用eval执行任意脚本。注意：eval在局部作用域中执行，而execScript在全局作用域中执行。
        /// </summary>
        public object Eval(string script)
        {
            Console.Write(ieWebBrowser.Document.ToString());
            var document = ieWebBrowser.Document;
            if (document == null) return null;
            var result = document.InvokeScript("eval", new object[] { script });
            return result;
        }

        #endregion

        #region ui
        public override void menu_max_Click(object sender, EventArgs e)
        {
            base.menu_max_Click(sender, e);
        }

        public override void menu_min_Click(object sender, EventArgs e)
        {
            base.menu_min_Click(sender, e);
        }

        public override void menu_close_Click(object sender, EventArgs e)
        {
            exit();
        }
        public override void menu_MouseHover(object sender, EventArgs e)
        {
            base.menu_MouseHover(sender, e);
        }

        public override void menu_MouseLeave(object sender, EventArgs e)
        {
            base.menu_MouseLeave(sender, e);
        }

        public override void menu_MouseMove(object sender, MouseEventArgs e)
        {
            base.menu_MouseMove(sender, e);
        }

        public override void drag_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Clicks > 1)
            {
                base.menu_max_Click(sender, e);
            }
            else
            {
                base.drag_MouseDown(sender, e);
            }
        }

        public void exit()
        {
            MessageBoxButtons messButton = MessageBoxButtons.OKCancel;
            DialogResult dr = MessageBox.Show("确定要退出吗?", "退出系统", messButton);
            if (dr == DialogResult.OK)
            {
                close();
            }
        }
         
        #endregion

        private void ieWebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            Console.Write("ieWebBrowser_DocumentCompleted");
            submitBtn.Enabled = true;
        }

        public void startTask()
        {
            string js = string.Empty;
            //登录账户密码
            foreach (var item in systemRule.LoginJS)
            {
                js = item.JS.Replace("$account", systemRule.Account).Replace("$password", systemRule.Password);
                if (item.JS.Contains("return "))
                {
                    ExeScript(js);
                }
                else
                {
                    Eval(js);
                }
                if (item.Second > 0)
                {
                    Delay(item.Second);
                }
            }
            //填写表单
            foreach (var item in systemRule.FormOptionJSList)
            {
                js = item.JS.Replace("$value", item.Value);
                if (item.JS.Contains("return "))
                {
                    ExeScript(js);
                }
                else
                {
                    Eval(js);
                }
                if (item.Second > 0)
                {
                    Delay(item.Second);
                }
            }
        }

        private void submitBtn_Click(object sender, EventArgs e)
        {
            startTask();
        }

        private void Delay(int second) //延迟系统时间，但系统又能同时能执行其它任务；
        {
            DateTime current = DateTime.Now;
            while (current.AddSeconds(second) > DateTime.Now)
            {
                Application.DoEvents();//转让控制权            
            }
            return;
        }
    }
}
